import axios_ from '@/utils/axios'
import { EventBus } from '@/store/index'
import { loginBlockAPI } from '@/store/modules/user'
import 'element-plus/es/components/message/style/css'
import { ElMessage, ElLoading } from 'element-plus'
import { nextTick } from 'vue'
// is mock ?
const isMock = false;//process.env.VUE_APP_MOCK == 'true';
const notNeedLoginUrls = ['/file/save'];

// 是否请求结束，防止二次请求；当同一条请求再次过来的时候，会进行判断（false：则执行；true：则阻截；）
let isApiSended = {}

// 请求时 Loading
let loadingInstance;
let options = { fullscreen: true }

// 请求地址前缀：域名+头
// export const serverUrl = "https://apib.hd.xxx.com/v1";
const env_ = import.meta.env;
const env = {
  webUrl: env_.VITE_APP_WEB_URL,
  apiUrl: env_.VITE_APP_API_URL,
};
export const serverUrl = env.apiUrl;
export const localUrl = "/";
// export const fileUploadUrl = "https://file.hd.xxx.com.sinacloud.net/";
export const fileUploadUrl = 'https://sinastorage.com/file.hd.xxx.com/';
// export const fileUploadUrl = process.env.NODE_ENV === 'production' ? 'https://sinastorage.com/file.hd.xxx.com/' : 'fileUpload'
// export const fileUploadUrl = "https://apib.hd.xxx.com/v1/file/upload";
// export const fileUploadS3Url = 'https://apib.hd.xxx.com/v1/weibo/picid/';
export const fileUploadS3Url = serverUrl + '/weibo/picid/';
// export const fileUploadS3Url = process.env.NODE_ENV === 'production' ? 'https://apib.hd.xxx.com/v1/weibo/picid/' : 's3FileUpload';



/** API
 * [API get/get4Data/post/post4Data]
 */
const API = class Api {
  constructor() {
    this.arrMockAPI = [  // 暂存 mock api
      '/stat/promt_list',
      '/stat/promt_add',
      '/site/add',
      '/site/save',
      '/site/get',
    ];
  }

  async get(url, params, cb) {
    axios_.request({
      url: url,
      method: 'get', // 默认是 get
      params: params,
      baseURL: isMock && this.arrMockAPI.indexOf(url) > -1 ? localUrl : serverUrl,
    }).then(function(response){
      cb(response.data.data);
    }).catch(function(response){
      ElMessage(url + response.data.msg)
    })
  }

  async get4Data(url, params, cb) {  // code / msg / data
    axios_.request({
      url: url,
      method: 'get', // 默认是 get
      params: params,
      baseURL: isMock && this.arrMockAPI.indexOf(url) > -1 ? localUrl : serverUrl,
    }).then(function(response){
      cb(response.data);
    }).catch(function(response){
      ElMessage(url + response.data.msg)
    })
  }

  async post(url, params, cb) {
    // isApiSended
    // eslint-disable-next-line no-prototype-builtins
    if(Object.prototype.hasOwnProperty.call(isApiSended, url) && notNeedLoginUrls.indexOf(url) == -1) {
      if(!isApiSended[url]){
        return
      }
    }else{
      isApiSended[url] = false
    }
    // loading
    loadingInstance = ElLoading.service(options);
    // post
    return await axios_.post(
      url,
      params)
      .then(function (response) {
        // loading close
        nextTick(() => {
          loadingInstance.close();
        });
        // isApiSended true
        isApiSended[url] = true;
        // code
        if(response.data.code == "900001"){
          EventBus.$emit("login")
          loginBlockAPI[url] = {url, params, cb}
        }
        if(response.data.code == 0){
          cb(response.data.data);
        }else{
          if(response.data && response.data.msg){
            ElMessage(url + response.data.msg)
          }
        }
      })
      .catch(function (response) {
        loadingInstance.close();
        nextTick(() => {
          if(response.data && response.data.msg){
            ElMessage(url + response.data.msg)
          }else{
            ElMessage(response.message)
          }
        });
        isApiSended[url] = true;
      })
  }

  async post4Data(url, params, cb) {  // code / msg / data
    if(Object.prototype.hasOwnProperty.call(isApiSended, url)){
      if(!isApiSended[url]){
        return
      }
    }else{
      isApiSended[url] = false
    }
    // loading
    loadingInstance = ElLoading.service(options);
    // post
    return await axios_.post(
      url,
      params)
      .then(function (response) {
        // loading close
        nextTick(() => {
          loadingInstance.close();
        });
        // isApiSended true
        isApiSended[url] = true;
        // code
        if(response.data.code == "900001"){
          EventBus.$emit("login")
          loginBlockAPI[url] = {url, params, cb}
        }
        // callback
        cb(response.data);
      })
      .catch(function (response) {
        nextTick(() => {
          loadingInstance.close();
          if(response.data && response.data.msg){
            ElMessage(url + response.data.msg)
          }else{
            ElMessage(response.message)
          }
        });
        cb(response.data)
        isApiSended[url] = true;
      })
  }
}

export const api = new API();
